package com.bonc.modules.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.bonc.common.utils.*;
import com.bonc.datasource.annotation.DataSource;
import com.bonc.modules.business.entity.TbCommonParamInfoEntity;
import com.bonc.modules.business.entity.TbWorkOrderInfoEntity;
import com.bonc.modules.business.entity.TbWorkOrderReplyEntity;
import com.bonc.modules.business.service.FileSystemService;
import com.bonc.modules.business.service.TbWorkOrderInfoService;
import com.bonc.modules.business.service.TbWorkOrderReplyService;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.bonc.modules.business.dao.TbWorkOederDistributionDao;
import com.bonc.modules.business.entity.TbWorkOederDistributionEntity;
import com.bonc.modules.business.service.TbWorkOederDistributionService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

@DataSource("data")
@Service("tbWorkOederDistributionService")
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任
public class TbWorkOederDistributionServiceImpl extends ServiceImpl<TbWorkOederDistributionDao, TbWorkOederDistributionEntity> implements TbWorkOederDistributionService {
    @Resource
    private TbWorkOederDistributionDao tbWorkOederDistributionDao;

    @Autowired
    private TbWorkOederDistributionService tbWorkOederDistributionService;

    @Autowired
    private TbWorkOrderInfoService tbWorkOrderInfoService;

    @Autowired
    private TbWorkOrderReplyService tbWorkOrderReplyService;

    @Autowired
    private FileSystemService fileSystemService;

    @Value("${iosServer.downloadUrl}")
    private String downloadUrl;

    @Value("${iosServer.uploadUrl}")
    private String uploadUrl;

    /**
     * 上正式环境修改
     */
    @Value("${uploadPath}")
    private String uploadPath;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String identifier = (String)params.get("identifier");
        IPage<TbWorkOederDistributionEntity> page = this.page(
                new Query<TbWorkOederDistributionEntity>().getPage(params),
                new QueryWrapper<TbWorkOederDistributionEntity>().like(StringUtils.isNotBlank(identifier),"identifier", identifier)
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getOrderDistributionListByParam(Map<String, Object> params) {
        IPage<TbWorkOederDistributionEntity> page = this.baseMapper.getOrderDistributionListByParam(new Query<TbWorkOederDistributionEntity>().getPage(params), params);
        return new PageUtils(page);
    }

    @Override
    public PageUtils getSqOrderDistributionListByParam(Map<String, Object> params) {
        IPage<TbWorkOederDistributionEntity> page = this.baseMapper.getSqOrderDistributionListByParam(new Query<TbWorkOederDistributionEntity>().getPage(params), params);
        return new PageUtils(page);
    }

    @Override
    public PageUtils getProblemOrderDistributionListByParam(Map<String, Object> params) {
        IPage<TbWorkOederDistributionEntity> page = this.baseMapper.getProblemOrderDistributionListByParam(new Query<TbWorkOederDistributionEntity>().getPage(params), params);
        return new PageUtils(page);
    }

    @Override
    public void downloadLocal(String path, HttpServletResponse response) throws IOException {
        // 读到流中
        InputStream inputStream = new FileInputStream(path);// 文件的存放路径
        response.reset();
        response.setContentType("application/octet-stream");
        String filename = new File(path).getName();
        filename = filename.substring(10);
        //防止中文文件名乱码
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }

    @Override
    public String uploadLocal(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        /*String date = DateUtils.format(new Date(), "yyyyMMdd");
        List<Map<String,Object>> list = tbWorkOederDistributionDao.getCountfromOrderDistribution(date);
        int count = 0;
        for(int i=0;i<list.size();i++){
            String attachList = list.get(i).get("ATTACH_LIST").toString();
            String str[] = attachList.split("\\|");
            count = count + str.length;
        }
        int counts = count+1;
        String xlh = "";
        if(count < 10){
            xlh = "00" + counts;
        }else if(count < 100 && count > 10){
            xlh = "0" + counts;
        }else{
            xlh = counts+"";
        }*/
        String dateTime = DateUtils.format(new Date(), "yyyy-MM-dd");
        String filePath = uploadPath + dateTime;
        System.out.println(filePath);
        File dest = new File(filePath + fileName);
        if(dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return "上传成功！";
        } catch (IOException e) {
            System.out.println(e.toString());
        }
        return "上传失败！";
    }

    @Override
    public boolean save(TbWorkOederDistributionEntity tbWorkOederDistribution) {
        return SqlHelper.retBool(this.getBaseMapper().insert(tbWorkOederDistribution));
    }

    @Override
    public TbWorkOederDistributionEntity getById(String id) {
        return this.getBaseMapper().selectById(id);
    }

    @Override
    public AtomicReference<String> postOrderDistributionService(TbWorkOederDistributionEntity orderDistribution) {
       /* LambdaQueryWrapper<TbWorkOederDistributionEntity> queryWrapper = new LambdaQueryWrapper<>();
        List<TbWorkOederDistributionEntity> list = tbWorkOederDistributionService.getOrderDistributionList();*/
        AtomicReference<String> res = new AtomicReference<>("");
        AtomicReference<String> req = new AtomicReference<>("");

        /*list.forEach(orderDistribution->{
        });*/

        String url = "http://10.254.30.252:3900/api/v2/sync/CSVC/DispatchCSS";
        SupermanUtil util = new SupermanUtil();

        JSONObject content = new JSONObject();

        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");

        String Identifier = dateFormat.format(calendar.getTime()) + "GZL" + "351" + AppUtils.getRandomReqNo();
        System.out.println("Identifier的取值为：" + Identifier);
        orderDistribution.setIdentifier(Identifier);
        orderDistribution.setOriginUnit("351");
        orderDistribution.setReceiverUnit("0057");
        orderDistribution.setCreatTime(dateFormat1.format(calendar.getTime()));

        content.put("Identifier", orderDistribution.getIdentifier());
        content.put("IdentyType", orderDistribution.getIdentyType());
        content.put("IdentySubtype", orderDistribution.getIdentySubtype());
        content.put("CreatorContactInfo", orderDistribution.getCreatorContactInfo());
        content.put("CreatTime", orderDistribution.getCreatTime());
        content.put("OriginUnit", orderDistribution.getOriginUnit());
        content.put("ReceiverUnit", orderDistribution.getReceiverUnit());
        content.put("Creator", orderDistribution.getCreator());
        content.put("Title", orderDistribution.getTitle());
        content.put("Content", orderDistribution.getContent());
        content.put("ProcessTime", orderDistribution.getProcessTime());
        content.put("ExtEarlyWarningLevel", orderDistribution.getExtEarlyWarningLevel());
        content.put("DataFileNameList", orderDistribution.getDataFileNameList());
        content.put("ExtEarlyWarningThreshold", orderDistribution.getExtEarlyWarningThreshold());

        StringBuffer buffer = new StringBuffer();
        StringBuffer buffer1 = new StringBuffer();
        //工单携带附件，做特殊处理
        int flags = 0;
        if(!StringUtils.isBlank(orderDistribution.getAttachList())) {
            System.out.println("工单携带附件，附件名为：" + orderDistribution.getAttachList());
            String str[] = orderDistribution.getAttachList().split("\\|");
            for (int j = 0; j < str.length; j++) {
                if(str.length > 1){
                    flags = j + 1;
                }
                String fileName = str[j];
                System.out.println(fileName);
                String filePath = uploadPath + "/" + DateUtils.format(new Date(), "yyyy-MM-dd");
                String fileNewName = fileSystemService.uploadFile3(uploadUrl, fileName, filePath, fileName, flags);
                String name = DateUtils.format(new Date(), "yyyy-MM-dd") + fileName;
                if (j == str.length - 1) {
                    buffer.append(fileNewName);
                    buffer1.append(name);
                } else {
                    buffer.append(fileNewName + "|");
                    buffer1.append(name + "|");
                }
            }
            content.put("AttachList", buffer);
        }else{
            content.put("AttachList", orderDistribution.getAttachList());
        }

        Map<String, Object> param = ResolveParamUtils.getAllParam(content);

        req.set(JSON.toJSONString(param));
        res.set(util.sendPost(url, req.get()));

        orderDistribution.setAttachList(buffer1.toString());
        boolean flag = tbWorkOederDistributionService.save(orderDistribution);
        System.out.println("工单创建并派发成功" + flag);
        TbWorkOrderInfoEntity tbWorkOrderInfo = new TbWorkOrderInfoEntity();
        //合并时需要修改
        tbWorkOrderInfo.setHandingTime(dateFormat1.format(calendar.getTime()));
        tbWorkOrderInfo.setIdentifier(orderDistribution.getIdentifier());
        tbWorkOrderInfo.setState("01");
        tbWorkOrderInfo.setHandingDepartment("中国移动通信集团山西有限公司综合部");
        tbWorkOrderInfo.setHandingOpinions("xxx");
        tbWorkOrderInfo.setHandlerContactInfor("13834576868");
        tbWorkOrderInfo.setHandler("填报人");
        tbWorkOrderInfoService.save(tbWorkOrderInfo);

        return res;
    }

    @Override
    public AtomicReference<String> SyncData(TbWorkOederDistributionEntity orderDistribution) {
        AtomicReference<String> res = new AtomicReference<>("");
        AtomicReference<String> req = new AtomicReference<>("");

        /*list.forEach(orderDistribution->{
        });*/

        String url = "http://10.254.30.252:3900/api/v2/sync/CSVC/SyncData";
        SupermanUtil util = new SupermanUtil();

        JSONObject content = new JSONObject();

        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");

        orderDistribution.setOriginUnit("351");
        orderDistribution.setReceiverUnit("0057");
        orderDistribution.setCreatTime(dateFormat1.format(calendar.getTime()));

        content.put("Identifier", orderDistribution.getIdentifier());
        content.put("IdentyType", orderDistribution.getIdentyType());
        content.put("IdentySubtype", orderDistribution.getIdentySubtype());
        content.put("ReceiverUnit", "0057");
        content.put("LaunchCompany", "351");

        //将工单paraList参数解析，加入其余参数再封装
        JSONArray jsonArray = JSONArray.fromObject(orderDistribution.getParaList());
        net.sf.json.JSONObject jsonobj = net.sf.json.JSONObject.fromObject(jsonArray.getJSONObject(0));
        jsonobj.put("CreatTime", orderDistribution.getCreatTime());
        jsonobj.put("OriginalUnit", orderDistribution.getOriginUnit());
        jsonobj.put("OriginReceiver", orderDistribution.getReceiverUnit());
        jsonobj.put("Creator", orderDistribution.getCreator());
        jsonobj.put("CreatorContactInfo", orderDistribution.getCreatorContactInfo());

        TbWorkOrderReplyEntity orderReply = tbWorkOrderReplyService.getById(orderDistribution.getIdentifier());
        jsonobj.put("Handler", orderReply.getHandler());
        jsonobj.put("HandlerInfor", orderReply.getHandlerInfor());
        jsonobj.put("HandingTime", orderReply.getHandingTime());
        jsonobj.put("HandlerRank", orderReply.getHandlerRank());
        jsonobj.put("HandingDepartment", orderReply.getHandingDepartment());
        jsonobj.put("AttachList", orderReply.getAttachList());
        jsonArray = JSONArray.fromObject(jsonobj);
        content.put("ParaList", jsonArray);


        System.out.println("------------" + content);
        Map<String, Object> param = ResolveParamUtils.getAllParam(content);
        System.out.println(param);

        /*req.set(JSON.toJSONString(param));
        res.set(util.sendPost(url, req.get()));*/

        return res;
    }

    @Override
    public String getTokenService() {
        String url = "http://10.254.30.252:3900/api/token/authinternal";
        SupermanUtil util = new SupermanUtil();
        String res = "";
        Map<String, String> param = new HashMap<>();
        param.put("appId","CSVB3510");
        param.put("appSecret","r1v7w0E84j");
        res = util.sendPost(url,param);
        net.sf.json.JSONObject jsonobj = net.sf.json.JSONObject.fromObject(res);
        String accessToken = jsonobj.get("access_token").toString();
        System.out.println(accessToken);
        return accessToken;
    }

    @Override
    public ReplyCommon DispatchCSS(TbCommonParamInfoEntity tbCommonParamValue) throws Exception {
        System.out.println(tbCommonParamValue);
        String content = "";
        String rspCode = "";
        String rspDesc = "";

        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat dateFormat1= new SimpleDateFormat("yyyyMMddHHmmss");
        String cutOffDay = dateFormat.format(calendar.getTime());
        String handingTime = dateFormat1.format(calendar.getTime());
        String transIDO = handingTime + System.currentTimeMillis();
        String providePartyID = "CSVB3510";

        /* 网状网已经校验 暂时屏蔽
        String signjy = ResolveParamUtils.analysisAllParam(tbCommonParamValue);
        if(sign == signjy || sign.equals(signjy)){

        }else {
            rspCode = "20207";
            rspDesc = "非法的签名";
        }*/

        content = tbCommonParamValue.getContent();
        System.out.println(content);
        TbWorkOederDistributionEntity distribution = JSONObject.parseObject(content,TbWorkOederDistributionEntity.class);
        System.out.println("-------------" + distribution);
        if(StringUtils.isBlank(distribution.getIdentifier()) || StringUtils.isBlank(distribution.getIdentyType()) ||
                StringUtils.isBlank(distribution.getIdentySubtype()) || StringUtils.isBlank(distribution.getTitle()) ||
                StringUtils.isBlank(distribution.getContent()) || StringUtils.isBlank(distribution.getOriginUnit()) ||
                StringUtils.isBlank(distribution.getReceiverUnit()) || StringUtils.isBlank(distribution.getCreatTime())){
            rspCode = "20101";
            rspDesc = "缺少必须的参数";
        }else{

            //新增工单——投诉焦点治理任务单（0206）
            /*if(distribution.getIdentySubtype().equals("0206")){
                if(StringUtils.isBlank(distribution.getGovernancemeasures()) || StringUtils.isBlank(distribution.getGoal()) ||
                        StringUtils.isBlank(distribution.getProcesstimes()) || StringUtils.isBlank(distribution.getEvaluation())){

                }

            }*/



            //新增必传参数校验
           /* if(distribution.getIdentySubtype().equals("0002") || distribution.getIdentySubtype().equals("0003")){//重点产品投诉预警单  投诉热点预警单
                if(StringUtils.isBlank(distribution.getExtEarlyWarningLevel())){
                    rspCode = "20101";
                    rspDesc = "缺少必须的参数";
                }
                return ReplyCommon.error(rspCode,rspDesc);
            }else if(distribution.getIdentySubtype().equals("0005") || distribution.getIdentySubtype().equals("0201")){//不知情定制预警单  不知情定制任务单
                if(StringUtils.isBlank(distribution.getDataFileNameList())){
                    rspCode = "20101";
                    rspDesc = "缺少必须的参数";
                }
                return ReplyCommon.error(rspCode,rspDesc);
            }else if(distribution.getIdentySubtype().equals("0006")){//产品洞察预警单
                if(StringUtils.isBlank(distribution.getExtEarlyWarningThreshold())){
                    rspCode = "20101";
                    rspDesc = "缺少必须的参数";
                }
                return ReplyCommon.error(rspCode,rspDesc);
            }*/

            //通过工单编号 判断该工单是否已经派发过 或者工单号使用重复
            TbWorkOederDistributionEntity redistribution = tbWorkOederDistributionService.getById(distribution.getIdentifier());
            if(redistribution != null){
                rspCode = "20000";
                rspDesc = "此工单编号已经派发过，请更换编号重试！";
            }else{
                if(!StringUtils.isBlank(distribution.getAttachList())){
                    distribution.setAnnexStatus("1");
                }

                //潜在不满客户预测预警单 0004 只有工单派发和工单归档接口  无特殊参数
                //不知情定制预警单  0005  全套流程  特殊参数 DataFileNameList
                //不知情定制任务单  0201  全套流程  特殊参数 DataFileNameList
                if(!StringUtils.isBlank(distribution.getDataFileNameList())){
                    //只要DataFileNameList字段不为空，则执行定时调度，获取附件并上传  不需再做特殊处理--cxy
                    distribution.setDatafileStatus("1");
                }

                /* 工单派发和附件下载不同步 10min后操作下载
                if(!StringUtils.isBlank(distribution.getAttachList())){
                    System.out.println("附件不为空，执行下载文件操作，下载之后将服务器目录下的文件删除" + distribution.getAttachList());
                    String str[] = distribution.getAttachList().split("\\|");

                    //将数据提供方上传至网状网平台的数据文件 通过sftp到平台指定服务器目录获取文件  保存到项目目录下
                    for(int j=0;j<str.length;j++){
                        String fileName = str[j];
                        System.out.println(fileName);
                        fileSystemService.downloadFile(downloadUrl,str[j],"/home/cusguoxin/sftpTest");
                        fileSystemService.deleteFile(downloadUrl,str[j]);

                        //下载并删除文件后，需要将文件统一上传至239目录下
                        File file = new File("/home/cusguoxin/sftpTest/"+str[j]);
                        fileSystemService.uploadFile(uploadUrl,file);
                    }
                }*/
                boolean num = tbWorkOederDistributionService.save(distribution);//将工单派发信息存入工单派发码表
                TbWorkOrderInfoEntity tbWorkOrderInfo = new TbWorkOrderInfoEntity();
                //合并时需要修改
                tbWorkOrderInfo.setHandingTime(handingTime);
                tbWorkOrderInfo.setIdentifier(distribution.getIdentifier());
                tbWorkOrderInfo.setState("01");
                tbWorkOrderInfo.setHandingDepartment("中国移动通信集团山西有限公司综合部");
                tbWorkOrderInfo.setHandingOpinions("xxx");
                tbWorkOrderInfo.setHandlerContactInfor("13834576868");
                tbWorkOrderInfo.setHandler("填报人");
                tbWorkOrderInfoService.save(tbWorkOrderInfo);

                /* 文件上传
                File file = new File("D:\\TDownload\\ceshiwendang.xlsx");
                fileSystemService.uploadFile(uploadUrl,file);*/

                if(num == true){
                    rspCode = "00000";
                    rspDesc = "success";
                }else{
                    rspCode = "20000";
                    rspDesc = "基础服务系统内部错误";
                }
            }
        }
        return ReplyCommon.ok(transIDO,cutOffDay,providePartyID,rspCode,rspDesc);
    }

    @Override
    public List<TbWorkOederDistributionEntity> getOrderDistributionList() {
        return tbWorkOederDistributionDao.getOrderDistributionList();
    }

    @Override
    public List<TbWorkOederDistributionEntity> getOrderDistributionAllList(String date) {
        return tbWorkOederDistributionDao.getOrderDistributionAllList(date);
    }

    @Override
    public List<TbWorkOederDistributionEntity> getOrderDistributionDataFileList() {
        return tbWorkOederDistributionDao.getOrderDistributionDataFileList();
    }

    @Override
    public boolean updateById(TbWorkOederDistributionEntity tbWorkOederDistributionEntity) {
        //return SqlHelper.retBool(this.getBaseMapper().updateById(TbWorkOederDistributionEntity));
        int total = tbWorkOederDistributionDao.updateById(tbWorkOederDistributionEntity);
        if(total > 0){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public List<Map<String, Object>> queryDistributionList() {
        return tbWorkOederDistributionDao.queryDistributionList();
    }

    @Scheduled(cron = "0 */5 * * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void getOrderAttachList() throws Exception {
        List<TbWorkOederDistributionEntity> list = tbWorkOederDistributionService.getOrderDistributionList();
        System.out.println("attachlist-------"+list.size());
        for(int i=0;i<list.size();i++){
            TbWorkOederDistributionEntity order = list.get(i);
            System.out.println("执行定时任务扫描sftp下载文件到本地......");
            String str[] = order.getAttachList().split("\\|");
            for(int j=0;j<str.length;j++){
                String fileName = str[j];
                System.out.println(fileName);
                fileSystemService.downloadFile(downloadUrl,str[j],"/home/cusguoxin/sftpTest");
                fileSystemService.deleteFile(downloadUrl,str[j]);
                //下载并删除文件后，需要将文件统一上传至239目录下
                System.out.println("执行上传任务");
                /*File file = new File("/home/cusguoxin/sftpTest/"+str[j]);
                fileSystemService.uploadFile1(downloadUrl,file);*/
                fileSystemService.uploadFile2(downloadUrl,fileName,"/home/cusguoxin/sftpTest/",fileName);
            }
            //将工单派发表附件状态改为2
            order.setAnnexStatus("2");
            tbWorkOederDistributionService.updateById(order);
        }
    }

    @Scheduled(cron = "0 */5 * * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void getOrderDataFileNameList() throws Exception {
        List<TbWorkOederDistributionEntity> list = tbWorkOederDistributionService.getOrderDistributionDataFileList();
        System.out.println("datafilelist-------"+list.size());
        for(int i=0;i<list.size();i++){
            TbWorkOederDistributionEntity order = list.get(i);
            System.out.println("执行定时任务扫描sftp下载文件到本地......");
            String str[] = order.getDataFileNameList().split("\\|");
            for(int j=0;j<str.length;j++){
                String fileName = str[j];
                System.out.println(fileName);
                fileSystemService.downloadFile(downloadUrl,str[j],"/home/cusguoxin/sftpTest");
                fileSystemService.deleteFile(downloadUrl,str[j]);
                //下载并删除文件后，需要将文件统一上传至239目录下
                System.out.println("执行上传任务");
                /*File file = new File("/home/cusguoxin/sftpTest/"+str[j]);
                fileSystemService.uploadFile1(downloadUrl,file);*/
                fileSystemService.uploadFile2(downloadUrl,fileName,"/home/cusguoxin/sftpTest/",fileName);
            }
            //将工单派发表附件状态改为2
            order.setDatafileStatus("2");
            tbWorkOederDistributionService.updateById(order);
        }
    }

    /**
     * 每天早上五点半生成前一天的对账工单明细数据
     * @throws Exception
     */
    //@Scheduled(cron = "0 */5 * * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void generateOrderInfoDetail(){
        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMdd");
        String filename = "GZLSEND_1002_351_";
        String today = dateFormat.format(calendar.getTime());
        filename += today+"_001";
        System.out.println(filename);
        SimpleDateFormat dateFormat1= new SimpleDateFormat("yyyyMMddHHmmss");
        String sjc = dateFormat1.format(calendar.getTime());
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        String yesterday = dateFormat.format(calendar.getTime());
        List<TbWorkOederDistributionEntity> list = tbWorkOederDistributionService.getOrderDistributionAllList(yesterday);

        //创建文件
        //File f = new File("d:\\"+ today + "\\" + filename);
        File f = new File(uploadUrl + today + "/" + filename);

        if(!f.getParentFile().exists()){
            f.getParentFile().mkdirs();
        }

        OutputStream out = null;
        try{
            out = new FileOutputStream(f);
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }

        //首行写入字符串
        String str = "10|1002|351|001|"+sjc+"|01|"+list.size()+"| |\n";
        System.out.println(str);
        for(int i=0;i<list.size();i++){
            str += list.get(i).getIdentifier() + "|" + list.get(i).getIdentyType() + "|" + list.get(i).getIdentySubtype() +"||\n";
        }

        // 将字符串转成字节数组
        byte b[] = str.getBytes();
        try
        {
            //将byte数组写入到文件之中
            out.write(b);
            out.close();
        }catch (IOException e1){
            e1.printStackTrace();
        }
        System.out.println("write end>>>>>>>>>>>");
    }
}
